package com.econ.powercloud.ems.util;

import com.alibaba.fastjson.JSON;
import com.econ.powercloud.ems.pojo.HeWeatherVO;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 天气预测
 */

@Component
public class WeatherForecastUtil {

    private static String API_URL = "https://free-api.heweather.net/s6/weather?key={key}&location={location}";

    private static String HF_KEY = "a09f3e2fc0fd436eb41ebec97d5dc3e1";

    private static String LOCATION = "CN101280101";//广州

    public HeWeatherVO getWeatherForecastInfo(String cityId){
        HeWeatherVO weatherVO = null;
        if(null == cityId || cityId.equals("")){
            cityId = LOCATION;
        }

        //设置超时时间
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(10*1000);
        requestFactory.setReadTimeout(10*1000);
        RestTemplate restTemplate = new RestTemplate(requestFactory);

        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("key",HF_KEY);
        paramMap.put("location",cityId);
        try {
            Map map = restTemplate.getForObject(API_URL,Map.class,paramMap);
            if(map!=null) {
                weatherVO = JSON.parseObject(JSON.toJSONString(map), HeWeatherVO.class);
            }
        } catch (RestClientException e) {
            e.printStackTrace();

        } finally {
            return weatherVO;
        }
    }

    public String getTmpMaxNextDay(String cityId){
        String res = "20";
        HeWeatherVO weatherVO = getWeatherForecastInfo(cityId);
        if(null != weatherVO){
            List<HeWeatherVO.HeWeather6.DailyForecast> dailyForecastList = weatherVO.getHeWeather6().get(0).getDaily_forecast();
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE,+1);
            Date date = calendar.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String nextDay = sdf.format(date);
            for(HeWeatherVO.HeWeather6.DailyForecast dailyForecast : dailyForecastList){
                if(dailyForecast.getDate().equals(nextDay)){
                    res = dailyForecast.getTmp_max();
                    System.out.println("日期:"+nextDay+"，最高气温:"+res);
                }
            }
        }else{
            return res;
        }
        return res;
    }

}
